﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BranchOfSansar.Sansar.Enquiry;
using DevExpress.XtraBars;
using System.IO;
using BranchOfSansar.Sansar.Register;
using DevExpress.XtraEditors;

namespace BranchOfSansar.Register.CallCenter
{
    public partial class frmCallList : Form
    {

        #region Load Functions
        public frmCallList()
        {
            InitializeComponent();
        }


        private void frmCallList_Load(object sender, EventArgs e)
        {
            if (File.Exists(this.Name + ".xml"))
            {
                viewCall.RestoreLayoutFromXml(this.Name + ".xml");
            }

            
            txtReceivedDate1.DateTime = DateTime.Now;
            txtDueDate1.DateTime = DateTime.Now;
            txtClosedDate1.DateTime = DateTime.Now;


            txtReceivedDate2.DateTime = DateTime.Now.AddDays(1);
            txtDueDate2.DateTime = DateTime.Now.AddDays(1);
            txtClosedDate2.DateTime = DateTime.Now.AddDays(1);

            BranchOfSansar.Sansar.Enquiry.Parameter[] paras;

            BranchOfSansar.Sansar.Enquiry.User[] usr;
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient ec = new Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                paras = ec.Parameters("(it.GroupCode='CS' OR it.GroupCode='CL' OR it.GroupCode='R1' OR it.GroupCode='R2' OR it.GroupCode='R3' OR it.GroupCode='NW' OR it.GroupCode='CP' OR it.GroupCode='DS' Or it.GroupCode='IT') AND it.Status=true ");
                usr = ec.Users("it.PositionNo='E'");
            }

            //Гүйцэтгэсэн хэрэглэгч
            txtDidUserNo.Properties.Items.AddRange(usr
                .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { IntValue = s.UserId, Display = s.Name })
                .ToArray());
            Globals.setComboSelectedItem(txtDidUserNo, 0);

            //Хүлээн авсан хэрэгэлгч
            txtReceivedUser.Properties.Items.AddRange(usr
                .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { IntValue = s.UserId, Display = s.Name })
                .ToArray());
            Globals.setComboSelectedItem(txtReceivedUser, Globals.UserId);

            //Төрөл
            var tlist = paras
                        .Where(w => w.GroupCode == "IT")
                        .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                        .ToList();
            tlist.Insert(0, new ComboItem() { Display = "[Дуудлага төрөл]", StrValue = "" });
            txtCallType.Properties.Items.AddRange(tlist.ToArray());
            txtCallType.SelectedIndex = 0;

            //Төлөв
            var slist=paras
                        .Where(w => w.GroupCode == "CS")
                        .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                        .ToList();
            slist.Insert(0,new ComboItem(){ Display="[Төлөв]", StrValue=""});
            txtStatus.Properties.Items.AddRange(slist.ToArray());
            txtStatus.SelectedIndex = 0;

            //Түвшин
            var llist = paras
                        .Where(w => w.GroupCode == "CL")
                        .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                        .ToList();
            llist.Insert(0, new ComboItem() { Display = "[Түвшин]", StrValue = "" });
            txtLevel.Properties.Items.AddRange(llist.ToArray());
            txtLevel.SelectedIndex = 0;

            #region Хүсэлт хаасан хэрэглэгч
            if (txtClosedUserNo.ShowToolTips)
            {
                txtClosedUserNo.Properties.Items.AddRange(usr
                    .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { IntValue = s.UserId, Display = s.Name })
                    .ToArray());
                Globals.setComboSelectedItem(txtClosedUserNo, 0);
            }
            #endregion

            #region Шалтгаан 1 Дамжуулах бүсээс
            if (txtR1.ShowToolTips)
            {
                txtR1.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "R1")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtR1.SelectedIndex = 0;
            }
            #endregion

            #region Шалтгаан 2 Хэрэглэгчийн буруутай
                txtR2.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "R2")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtR2.SelectedIndex = 0;            
            #endregion

            #region Шалтгаан 3 Бусад
                txtR3.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "R3")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtR3.SelectedIndex = 0;            
            #endregion

            #region Дүүрэг
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient ec = new Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                var dis = ec.DistrictList();
                var dlist = dis
                   .Select(s => new ComboItem() { StrValue = s.DistrictCode, Display = s.Name })
                   .ToList();
                dlist.Insert(0, new ComboItem() { Display = "[Дүүрэг]", StrValue = "" });
                txtDistrict.Properties.Items.AddRange(dlist.ToArray());
                txtDistrict.SelectedIndex = 0;
            }
            #endregion

            #region Сүлжээ
            var nlist = paras
              .Where(w => w.GroupCode == "NW")
              .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
              .ToList();
            nlist.Insert(0, new ComboItem() { Display = "[Сүлжээ]", StrValue = "" });
            txtNetwork.Properties.Items.AddRange(nlist.ToArray());
            txtNetwork.SelectedIndex = 0;
            #endregion

            #region Тайлбар
            txtDesc.Properties.Items.AddRange(paras
              .Where(w => w.GroupCode == "DS")
              .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
              .ToArray());
            txtDesc.SelectedIndex = 0;
            #endregion

            #region Гомдолын төрөл
            txtComplain.Properties.Items.AddRange(paras
               .Where(w => w.GroupCode == "CP")
               .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
               .ToArray());
            txtComplain.SelectedIndex = 0;
            #endregion

            #region Хэсэгийн дугааруудыг оруулах
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient ec = new Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                var parts = ec.PartList().ToArray();
                var plist = parts
                 .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { IntValue = s.PartNo, Display = s.Name })
                 .ToList();
                plist.Insert(0, new ComboItem() { Display = "[Хэсэг]", IntValue = 0 });
                txtPart.Properties.Items.AddRange(plist.ToArray());
                txtPart.SelectedIndex = 0;
            }
            #endregion

        }

        private void frmCallList_FormClosing(object sender, FormClosingEventArgs e)
        {
            viewCall.SaveLayoutToXml(this.Name + ".xml");
        }
        #endregion



        protected void txtContractNo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            BranchOfSansar.Register.Main.frmContractList frm = new BranchOfSansar.Register.Main.frmContractList(true);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtContractNo.Text = frm.Contract.ContractNo.ToString();
            }
        }


        private void btnSearch_Click(object sender, EventArgs e)
        {
            using (BranchOfSansar.Sansar.Register.RegisterClient rc = new Sansar.Register.RegisterClient(Globals.Token))
            {
                gridCall.DataSource = rc.CallRequestList(DefineQuery());
            }
        }

        private string GetValue(ComboBoxEdit cmb)
        {
            return ((ComboItem)cmb.SelectedItem).StrValue;
        }

        private int GetIntValue(ComboBoxEdit cmb)
        {
            return ((ComboItem)cmb.SelectedItem).IntValue;
        }

        private string DefineQuery()
        {
            StringBuilder build = new StringBuilder(1000);
            long temp = 0;

            if (!string.IsNullOrEmpty(txtUserNo.Text.Trim()))
                build.Append(string.Format(" and it.UserName='{0}'", txtUserNo.Text));

            if(!string.IsNullOrEmpty(txtContractNo.Text.Trim()) && long.TryParse(txtContractNo.Text,out temp))
                build.Append(string.Format(" and it.ContractNo={0}", txtContractNo.Text));

            if(!string.IsNullOrEmpty(txtPhone.Text.Trim()))
                build.Append(string.Format(" and it.PhoneNumber='{0}'", txtPhone.Text));

            if(txtDistrict.SelectedIndex>0)
                build.Append(string.Format(" and it.DistrictCode='{0}'", GetValue(txtDistrict)));

            if(txtQuarter.SelectedIndex>0)
                build.Append(string.Format(" and it.QuarterCode='{0}'", GetValue(txtQuarter)));

            if (txtPart.SelectedIndex > 0)
                build.Append(string.Format(" and it.PartNo={0}", GetIntValue(txtPart)));

            if (txtSection.SelectedIndex > 0)
                build.Append(string.Format(" and it.SectionNo='{0}'", GetValue(txtSection)));
            
            if (!string.IsNullOrEmpty(txtApartNo.Text) && long.TryParse(txtApartNo.Text,out temp))
                build.Append(string.Format(" and it.ApartNo='{0}'", txtApartNo.Text));

            if (!string.IsNullOrEmpty(txtDoorNo.Text) && long.TryParse(txtDoorNo.Text, out temp))
                build.Append(string.Format(" and it.DoorNo='{0}'", txtDoorNo.Text));

            if(txtReceivedUser.SelectedIndex>0)
                build.Append(string.Format(" and it.UserNoOfReceived={0}", GetIntValue(txtReceivedUser)));

            if (txtClosedUserNo.SelectedIndex > 0)
                build.Append(string.Format(" and it.UserNoOfClosed={0}", GetIntValue(txtClosedUserNo)));

            if (txtDidUserNo.SelectedIndex > 0)
                build.Append(string.Format(" and it.UserNoOfDid={0}", GetIntValue(txtDidUserNo)));

            if (chkReceived.Checked)
                build.Append(string.Format(" and it.DateOfReceived>=DateTime'{0} 00:00' and it.DateOfReceived<=DateTime'{1} 23:59' ", txtReceivedDate1.DateTime.ToString("yyyy-M-d"), txtReceivedDate2.DateTime.ToString("yyyy-M-d")));

            if (chkClosed.Checked)
                build.Append(string.Format(" and it.DateOfClosed>=DateTime'{0} 00:00' and it.DateOfClosed<=DateTime'{1} 23:59' ", txtClosedDate1.DateTime.ToString("yyyy-M-d"), txtClosedDate2.DateTime.ToString("yyyy-M-d")));

            if (chkFinish.Checked)
                build.Append(string.Format(" and it.DateOfPlaning>=DateTime'{0} 00:00' and it.DateOfPlaning<=DateTime'{1} 23:59' ", txtDueDate1.DateTime.ToString("yyyy-M-d"), txtDueDate2.DateTime.ToString("yyyy-M-d")));


            if (txtCallType.SelectedIndex > 0)
                build.Append(string.Format(" and it.ReqTypeNo='{0}'", GetValue(txtCallType)));

            if (txtStatus.SelectedIndex > 0)
                build.Append(string.Format(" and it.StatusNo='{0}'", GetValue(txtStatus)));

            if (txtLevel.SelectedIndex > 0)
                build.Append(string.Format(" and it.LevelNo='{0}'", GetValue(txtLevel)));

            if (txtNetwork.SelectedIndex > 0)
                build.Append(string.Format(" and it.Network='{0}'", GetValue(txtNetwork)));

           

            string res = build.ToString();
            if (res.Length > 0)
                return res.Substring(4, res.Length - 4);
            else
                return "";
        }
  

        private void gridCall_DoubleClick(object sender, EventArgs e)
        {
            if (viewCall.SelectedRowsCount > 0)
            {
                var item = (vw_CallRequest)viewCall.GetRow(viewCall.GetSelectedRows()[0]);
                Form frm=null;
                switch (item.ReqTypeNo)
                {
                    case "CMP": frm = new frmCallCMP(item); break;
                    case "IRS": frm = new frmCallIRS(item); break;
                    case "ODR": frm = new frmCallODR(item); break;
                    case "OTR": frm = new frmCallOTR(item); break;
                    case "SER": frm = new frmCallSER(item); break;
                    default: break;
                }

                if (frm == null)
                {
                    Globals.Warr("Цонх олдсонгүй!");
                    return;
                }

                
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    btnSearch_Click(sender, e);
                }
            }
        }

        private void chkReceived_CheckedChanged(object sender, EventArgs e)
        {
            txtReceivedDate1.Enabled = chkReceived.Checked;
            txtReceivedDate2.Enabled = chkReceived.Checked;
        }

        private void chkFinish_CheckedChanged(object sender, EventArgs e)
        {
            txtDueDate1.Enabled = chkFinish.Checked;
            txtDueDate2.Enabled = chkFinish.Checked;
        }

        private void chkClosed_CheckedChanged(object sender, EventArgs e)
        {
            txtClosedDate1.Enabled = chkClosed.Checked;
            txtClosedDate2.Enabled = chkClosed.Checked;
        }

        private void txtDistrict_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient ec = new Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                txtQuarter.Properties.Items.Clear();

                string dis_code = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtDistrict.SelectedItem).StrValue;
                //Хороо
                txtQuarter.Properties.Items.AddRange(ec.QuarterList(dis_code)
                    .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.QuarterCode, Display = s.Name })
                    .ToArray());
                txtQuarter.SelectedIndex = txtQuarter.Properties.Items.Count > 0 ? 0 : -1;

                txtSection.Properties.Items.Clear();
                //Хороолол
                txtSection.Properties.Items.AddRange(ec.SectionListByDisctrict(dis_code)
                    .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { IntValue = (int)s.SectionNo, Display = s.Name })
                    .ToArray());
                txtSection.SelectedIndex = txtSection.Properties.Items.Count > 0 ? 0 : -1;
            }
        }

        private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

    

    }
}
